package com.xdja.study;
import com.xdja.study.http.HttpClientVerticle;
import com.xdja.study.mysql.dao.UserConfigDaoVerticle;
import com.xdja.study.mysql.dao.UserDaoVerticle;
import com.xdja.study.redis.UserRedisVerticle;
import com.xdja.study.util.PropertiesUtils;
import com.xdja.study.util.StringUtils;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;
import java.util.Properties;

@SpringBootApplication
public class VertxStudyApplication {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private AppConfiguration appConfiguration;
    @Autowired
    private HttpRouteVerticle httpRouteVerticle;
    @Autowired
    private UserDaoVerticle userDaoVerticle;
    @Autowired
    private UserConfigDaoVerticle userConfigDaoVerticle;
    @Autowired
    private UserRedisVerticle userRedisVerticle;
    @Autowired
    private HttpClientVerticle httpClientVerticle;




    public static void main(String[] args) {
        SpringApplication.run(VertxStudyApplication.class, args);

    }

    @PostConstruct
    public void deployVerticle() {
        Vertx vertx = Vertx.vertx();
        //1.通过hikari连接，且jdbc参数读取配置文件
        PropertiesUtils hjp = new PropertiesUtils("hikariCP.jdbc.properties");
        Properties jdbcProp = hjp.getProperties();
        JsonObject jdbcClientConfig = new JsonObject();
        jdbcProp.keySet().forEach(key -> {
            String value = jdbcProp.getProperty(key.toString());
            jdbcClientConfig.put(key.toString(), StringUtils.isInteger(value) ? Integer.valueOf(value) : value);
        });
        DeploymentOptions jdbcClientOptions = new DeploymentOptions().setConfig(jdbcClientConfig);
        vertx.deployVerticle(userConfigDaoVerticle, jdbcClientOptions);
        logger.debug("userConfigDaoVerticle");
        //2.不通过hikari连接，且jdbc参数硬编码
//        vertx.deployVerticle(userDaoVerticle);
        //3.部署redis查询
        vertx.deployVerticle(userRedisVerticle);
        //4.部署httpClient
        int workerPoolSize = appConfiguration.workerPoolSize();
        if(workerPoolSize <= 0) {
            vertx.deployVerticle(httpClientVerticle);
        } else {//以worker的形式运行
            DeploymentOptions httpClientOptions = new DeploymentOptions().setWorker(true).setWorkerPoolSize(appConfiguration.workerPoolSize());
            vertx.deployVerticle(httpClientVerticle, httpClientOptions);
        }
        //5.启动http服务,并根据路径分发路由
        vertx.deployVerticle(httpRouteVerticle);
        logger.debug("启动完httpVerticle");
    }

}
